<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Ali\Api;
use App\Http\Controllers\Ali\DysmsController;
use App\Jobs\SampleInfoExpireController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Schema;

class SmsController extends Controller
{
    private $template = '尊敬的${name}，您有${num}件工器具的合格证即将到期，请及时进行复检！';

    //通知列表
    public function index(Request $request) {
        if($request->expectsJson()) {
            $data = DB::table('a_sms_log')->orderBy('ctime', 'desc')->get();
            $jsonData['data'] = $data;
            return response()->json($jsonData);
        }
        else {
            $data = [];
            $data['setting_sms'] = json_decode(DB::table('setting_sys')->where('key', 'sms')->value('value'), true);
            $data['sending_count'] = DB::table('a_sms_log')->where('status', 1)->count();
            return view('admin.sms.index', compact('data'));
        }
    }

    //发送详情
    public function detail($id) {
        $log = DB::table('a_sms_log')->find($id);
        $BizId = $log->BizId;
        $date = str_replace('-', '', substr($log->send_date, 0, 10));
        $params = ['CurrentPage' => 1, 'PageSize' => 10, 'PhoneNumber' => $log->mobile, 'SendDate' => $date, 'BizId' => $BizId,];
        $sms = new DysmsController();
        $data = $sms->QuerySendDetails($params);
        $data = json_decode($data, true);

        $status = $log->status;
        if($data['Code'] !== 'OK' || $data['Message'] !== 'OK') {
            return '查询失败！';
        }
        $failCount = 0;
        $tempStat = [];
        if(isset($data['SmsSendDetailDTOs']['SmsSendDetailDTO'])) {
            $items = $data['SmsSendDetailDTOs']['SmsSendDetailDTO'];
            foreach($items as $item) {
                $tempStat[] = $item['SendStatus'];
            }
            $valCount = array_count_values($tempStat);
            $failCount = $s2 = isset($valCount[2]) ? $valCount[2] : 0;
            $s3 = isset($valCount[3]) ? $valCount[3] : 0;
            if($data['TotalCount'] == $s3) {
                $status = 3;
            }
            else if($data['TotalCount'] == $s2) {
                $status = 2;
            }
            else if($data['TotalCount'] > $s3 && $s3 > 0) {
                $status = 4;
            }
            else {
                $status = 1;
            }
            DB::table('a_sms_log')->where('id', $id)->update(['status' => $status]);
        }
        if($failCount > 0) {
            $set = DB::table('setting_sys')->where('key', 'sms')->value('value');
            $set = json_decode($set, true);
            $set['count'] += $failCount;
            DB::table('setting_sys')->where('key', 'sms')->update(['value' => json_encode($set)]);
        }

        return view('admin.sms.detail', compact('data'));
    }

    //设置
    public function set(Request $request) {
        if($request->isMethod('POST')) {
            $input = $request->only('is_open', 'gqj_notice_early_days', 'gqj_notice_loop_days', 'gqj_notice_delay_days');
            $host = $request->getHost();
            if($input['is_open'] === 'on') {
                if(DB::connection("mysql_HuiBangJianCe")->table('sample_info_exipre_notice_url')->where('url', $host)->doesntExist()) {
                    DB::connection("mysql_HuiBangJianCe")->table('sample_info_exipre_notice_url')->insert(['url' => $host]);
                }
            }
            else {
                DB::connection("mysql_HuiBangJianCe")->table('sample_info_exipre_notice_url')->where(['url' => $host])->delete();
            }
            //插入数据    insert 返回true 或 false
            if(DB::table('setting_sys')->where('key', 'sms')->doesntExist()) {
                $input['count'] = 0;
                $input = json_encode($input);
                $result = DB::table('setting_sys')->where('key', 'sms_open')->insert(['key' => 'sms', 'value' => $input, 'remark' => '短信开关']);
            }
            else {
                $updata = ['value->is_open' => $input['is_open'], 'value->gqj_notice_early_days' => $input['gqj_notice_early_days'], 'value->gqj_notice_loop_days' => $input['gqj_notice_loop_days'], 'value->gqj_notice_delay_days' => $input['gqj_notice_delay_days'],];
                $result = DB::table('setting_sys')->where('key', 'sms')->update($updata);
            }
            setCache('setting');

            //由于框架自身不支持响应bool值，所以转化一种形式
            return intval($result);
        }
        else {
            $data = [];
            $set = DB::table('setting_sys')->where('key', 'sms')->value('value');
            $data['set'] = json_decode($set, true);
            $data['gqj_set'] = DB::table('a_sms_gqj_set as a')
                                 ->leftJoin('a_std_tool_rel as b', 'a.std_tool_rel_id', '=', 'b.id')
                                 ->leftJoin('a_tool as c', 'b.tool_id', '=', 'c.id')
                                 ->leftJoin('a_standard as d', 'b.std_id', '=', 'd.id')
                                 ->select('a.*', 'c.name as tool_name', 'd.num as std_num', 'b.cycle')
                                 ->get();
            return view('admin.sms.set', compact('data'));
        }
    }

    //微信通知规则 添加
    public function add(Request $request) {
        if($request->isMethod('POST')) {
            $post_data = $request->only(['wechat_notice_id', 'manager_id']);
            try {
                //插入数据    insert 返回true 或 false
                $result = DB::table('a_wx_manager_rel')->insert($post_data);
            } catch(\Throwable $e) {
                return '2';
            }
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? '1' : '0';
        }
        else {
            $manager = DB::table('manager')->select('id', 'username', 'realname')->where('status', '2')->get();
            $a_wechat_notice = DB::table('a_wechat_notice')->get();
            return view('admin . sms . add', compact('manager', 'a_wechat_notice'));
        }
    }

    //删除
    public function del(Request $request) {
        $id = $request->id;

        // delete 返回受影响的行数
        $result = DB::table('a_sms_log')->where(['id' => $id, 'status' => 2])->delete();

        //由于框架自身不支持响应bool值，所以转化一种形式
        return (int)$result;
    }

    //购买--添加
    public function buyAdd() {
        $data = [];
        $data['realname'] = auth('admin')->user()->realname;
        if(request()->method() === 'POST') {
            $indata = request()->only('unit_price', 'price', 'is_paid', 'inv_code', 'inv_no', 'inv_date');
            $exists = DB::table('a_sms_buy')->where('inv_code', $indata['inv_code'])->orWhere('inv_no', $indata['inv_no'])->exists();
            if($exists) {
                return '发票代码/编号已存在';
            }
            $indata['sms_num'] = ceil($indata['price']*100/$indata['unit_price']);
            $indata['realname'] = auth('admin')->user()->realname;
            $indata['manager_id'] = auth('admin')->user()->id;
            if(!$indata['inv_date']) {
                unset($indata['inv_date']);
            }
            $res = DB::table('a_sms_buy')->insert($indata);
            $msg = $res ? '添加成功，待审核！' : '添加失败！';
            return $msg;
        }
        return view('admin.sms.buy.add', compact('data'));
    }

    //购买记录
    public function buyIndex() {
        $data = [];
        $data['setting_sms'] = json_decode(DB::table('setting_sys')->where('key', 'sms')->value('value'), true);
        $data['list'] = DB::table('a_sms_buy')->orderBy('id', 'desc')->get();
        return view('admin.sms.buy.index', compact('data'));
    }

    //购买记录 -- 删除
    public function buyDel($id) {
        // delete 返回受影响的行数
        $result = DB::table('a_sms_buy')->where(['id' => $id, 'is_paid' => 1, 'audit' => 1])->delete();

        //由于框架自身不支持响应bool值，所以转化一种形式
        return (int)$result;
    }

    //购买记录 -- 审核
    public function buyAudit($id, $stat) {
        if(DB::table('a_sms_buy')->where('id', $id)->value('audit') > 1) {
            return '已审核';
        }
        // delete 返回受影响的行数
        DB::beginTransaction();
        try {
            DB::table('a_sms_buy')->where(['id' => $id, 'is_paid' => 2])->update([
                'audit'            => $stat,
                'audit_manager_id' => auth('admin')->user()->id,
                'audit_realname'   => auth('admin')->user()->realname
            ]);
            $setting = DB::table('setting_sys')->where('key', 'sms')->value('value');
            $setting = json_decode($setting, true);
            $addNum = DB::table('a_sms_buy')->where('id', $id)->value('sms_num');
            $setting['count'] += $addNum;
            DB::table('setting_sys')->where('key', 'sms')->update([
                'value' => json_encode($setting)
            ]);
        } catch(\Exception $e) {
            DB::rollBack();
            return $e->getMessage();
        }
        DB::commit();
        //由于框架自身不支持响应bool值，所以转化一种形式
        return 1;
    }

    //更新短信状态
    public function upSmsStatus() {
        set_time_limit(0);
        ini_set('max_execution_time', 0);
        ini_set('memory_limit', - 1);
        $data = DB::table('a_sms_log')->where('status', 1)->get();
        $sms = new DysmsController();
        $failCount = 0;
        foreach($data as $k => $val) {
            $phoneNumber = $val->mobile;
            $bizid = $val->BizId;
            $date = str_replace('-', '', substr($data->ctime, 0, 10));
            $params = ['CurrentPage' => 1, 'PageSize' => 10, 'PhoneNumber' => $phoneNumber, 'SendDate' => $date, 'BizId' => $bizid];     //手机号默认空，在循环中添加
            $res1 = $sms->QuerySendDetails($params);
            //修改返回值
            $res = json_decode($res1);
            if($res->Code === 'OK' && $res->Message === 'OK') {
                $TotalCount = $res->TotalCount;
                if(isset($res->SmsSendDetailDTOs->SmsSendDetailDTO)) {
                    $detail = $res->SmsSendDetailDTOs->SmsSendDetailDTO;
                    $statusAry = [];
                    foreach($detail as $index => $item) {
                        array_push($statusAry, intval($item->SendStatus));
                    }

                    $ary = array_count_values($statusAry);
                    $s1 = intval(isset($ary[1]) ? $ary[1] : 0);
                    $s2 = intval(isset($ary[2]) ? $ary[2] : 0);
                    $s3 = intval(isset($ary[3]) ? $ary[3] : 0);
                    $status = 2;  //默认发送失败
                    if($s3 == $TotalCount) {
                        $status = 3;
                    }
                    else {
                        if($s3 > 0 && $s2 > 0) {
                            $status = 4;
                        }
                        if($s2 == $TotalCount) {
                            $status = 2;
                        }
                        if($s1 > 0) {
                            $detail['sendingCount'] = $s1;
                        }
                    }
                    //增加失败的短信条数
                    $failCount += $s2;
                    // 修改日志
                    //						DB::table('a_sms_log')->where('BizId', $bizid)->where('mobile', $phoneNumber)->update(['status' => $status, 'back' => json_encode($detail)]);
                }
            }
        }
    }

    //签名记录
    public function signIndex() {
        $data = [];
        $data['list'] = DB::table('a_sms_sign')->orderBy('ctime', 'desc')->get();
        return view('admin.sms.sign.index', compact('data'));
    }

    //签名记录--添加
    public function signAdd() {
        $data = [];
        $user = auth('admin')->user();
        $data['realname'] = $user->realname;
        if(request()->method() === 'POST') {
            $indata = request()->only('name', 'remark');

            $SMS = new DysmsController();
            $param = ['SignName' => $indata['name'], 'Remark' => $indata['remark']];
            $SignFileList = [['FileSuffix' => 'png', 'FileContents' => base64_encode(file_get_contents('admin/static/h-ui/images/validform/iconpic-error.png'))]];
            $SignFileList1 = [];
            foreach($SignFileList as $k => $v) {
                $k += 1;
                foreach($v as $i => $value) {
                    $SignFileList1["SignFileList.$k.$i"] = $value;
                }
            }
            $param['SignFileList'] = $SignFileList1;
            $res = $SMS->AddSmsSign($param);
            if($res->Message === 'OK' && $res->Code === 'OK') {
                $indata['realname'] = $user->realname;
                $indata['manager_id'] = $user->id;
                $res = DB::table('a_sms_sign')->insert($indata);
                $msg = $res ? '操作成功！待审核！' : '操作失败！';
            }
            else {
                $msg = $res->Message;
            }
            return $msg;
        }
        return view('admin.sms.sign.add', compact('data'));
    }

    //签名记录--修改
    public function signEdit($id) {
        $user = auth('admin')->user();
        $data = DB::table('a_sms_sign')->find($id);
        if($data->manager_id != $user->id) {
            return '只能修改自己添加的签名';
        }
        if(request()->method() === 'POST') {
            $updata = request()->only('name', 'remark');
            if($updata['name'] === $data->name && $updata['remark'] == $data->remark) {
                return '请先修改数据！';
            }

            $SMS = new DysmsController();
            $param = ['Action' => 'ModifySmsSign', 'SignName' => $updata['name'], 'Remark' => $updata['remark']];
            $SignFileList = [['FileSuffix' => 'jpg', 'FileContents' => base64_encode(file_get_contents('admin/myImg/Business-License.jpg'))]];
            $SignFileList1 = [];
            foreach($SignFileList as $k => $v) {
                $k += 1;
                foreach($v as $i => $value) {
                    $SignFileList1["SignFileList.$k.$i"] = $value;
                }
            }
            $param['SignFileList'] = $SignFileList1;
            $res = $SMS->AddSmsSign($param);
            if($res->Message === 'OK' && $res->Code === 'OK') {
                $updata['realname'] = $user->realname;
                $updata['status'] = 0;
                $res = DB::table('a_sms_sign')->where('id', $id)->update($updata);
                $msg = $res ? '操作成功！待审核！' : '操作失败！';
            }
            else {
                $msg = $res->Message;
            }
            return $msg;
        }
        $data->back = json_decode($data->back);
        return view('admin.sms.sign.edit', compact('data'));
    }

    //签名记录 -- 删除
    public function signDel($id) {
        $info = DB::table('a_sms_sign')->find($id);
        if(DB::table('a_sms_log')->where('sign_name', $info->name)->exists()) {
            return out(0, '签名使用过，无法删除！');
        }
        $SMS = new DysmsController();
        $param = ['SignName' => $info->name];
        $res = $SMS->DeleteSmsSign($param);
        if($res->Message === 'OK' && $res->Code === 'OK') {
            $res = DB::table('a_sms_sign')->where(['id' => $id])->delete();
            return $res ? out(1, '删除成功！') : out(0, '删除失败！');
        }
        else {
            return out(0, $res->Message);
        }
    }

    //签名记录 -- 设置默认
    public function signDef($id) {
        DB::beginTransaction();
        try {
            DB::table('a_sms_sign')->where('is_def', 1)->update(['is_def' => 0]);
            DB::table('a_sms_sign')->where('id', $id)->update(['is_def' => 1]);
            DB::commit();
        } catch(\Exception $e) {
            DB::rollBack();
            return out(0, '设置失败！'.$e->getMessage());
        }
        return out(1, '设置成功！');
    }

    //审核详情
    public function signDetail($id) {
        $info = DB::table('a_sms_sign')->find($id);
        $SMS = new DysmsController();
        $param = ['SignName' => $info->name];
        $res = $SMS->QuerySmsSign($param);
        $back = json_encode($res);
        if($res->Message === 'OK' && $res->Code === 'OK') {
            DB::table('a_sms_sign')->where('id', $id)->update(['status' => $res->SignStatus, 'back' => $back]);
            return out(1, '', $res);
        }
        else {
            DB::table('a_sms_sign')->where('id', $id)->update(['status' => 2, 'back' => $back]);
            return out(0, $res->Message);
        }
    }

    //重新发送短信
    public function sendOne() {
        //短信设置
        $smsSet = json_decode(DB::table('setting_sys')->where('key', 'sms')->value('value'));
        $id = request('id', '');
        try {
            $log = DB::table('a_sms_log')->find($id);
            $content = $log->content;
            $SMS = new DysmsController();
            $params = [
                'PhoneNumbers'  => $log->mobile,
                'SignName'      => config('constant.alidysms_sign') ? config('constant.alidysms_sign') : '汇邦检测',
                'TemplateCode'  => 'SMS_218160860',
                'TemplateParam' => $log->param ?: ['name' => $log->client_name, 'num' => intval(explode('您有', $content)[1])],
            ];
            $res = $SMS->SendSms($params);
            $res = json_decode($res);
            if($res->Code === 'OK' && $res->Message === 'OK') {
                //修改日志信息
                DB::table('a_sms_log')->where('id', $id)->update(['BizId' => $res->BizId, 'send_date' => date('Y-m-d H:i:s'), 'status' => 1]);
                //减少短信数量
                $smsSet->count -= 1;
                DB::table('setting_sys')->where('key', 'sms')->update(['value' => json_encode($smsSet)]);
            }
            return $res->Message;
        } catch(\Exception $exception) {
            return 0;
        }
        return 1;
    }

    //工器具规则设置
    public function gqjSet() {
        if(request()->isMethod('post')) {
            $method = request('method', '');
            if($method !== 'del') {
                $setting = json_decode(getCache('setting')['sms']);
                if(request('early_days', 0) == 0 && request('loop_days', 0) == 0 && request('delay_days', 0) == 0) {
                    return '设置错误！';
                }
                if($setting->gqj_notice_early_days == request('early_days') && $setting->gqj_notice_loop_days == request('loop_days') && $setting->gqj_notice_delay_days == request('delay_days')) {
                    return '统一设置可以满足您的需求，不需要重复添加~';
                }
            }
            switch($method) {
                case 'add':
                    if(DB::table('a_sms_gqj_set')->where('std_tool_rel_id', request('std_tool_rel_id'))->exists()){
                        return '已存在！请先删除！';
                    }
                    $res = DB::table('a_sms_gqj_set')->insert([
                        'std_tool_rel_id' => request('std_tool_rel_id'),
                        'early_days'      => request('early_days'),
                        'loop_days'       => request('loop_days'),
                        'delay_days'      => request('delay_days'),
                    ]);
                    break;
                case 'del':
                    $res = DB::table('a_sms_gqj_set')->where('id', request('id'))->delete();
                    break;
                default:
                    $res = 0;
                    break;
            }
            return $res ? 1 : 0;
        }
        $std_tool_rels = DB::table('a_std_tool_rel as a')
                           ->leftJoin('a_tool as b', 'a.tool_id', '=', 'b.id')
                           ->leftJoin('a_standard as c', 'a.std_id', '=', 'c.id')
                           ->where('b.ishide', '0')
                           ->select('a.*', 'b.name as tool_name', 'c.num as std_num')
                           ->get();
        $data = [];
        foreach($std_tool_rels as $rel) {
            $data[$rel->tool_name][$rel->std_num] = $rel;
        }
        return view('admin.sms.gqj.set', compact('data'));
    }
}
